package com.zcyr.util;

import java.util.HashMap;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zcyr.constant.StatusCode;
/**
 * 基础响应体, 所有json接口应该使用该响应体
 * {
 *     code: int,
 *     msg: String
 *     ...key: value
 * }
 * @author zcyr
 */
public class JsonBody extends HashMap<String, Object> {

    private JsonBody(StatusCode code, String msg) {
        super.put("code", code.getValue());
        super.put("msg", msg);
    }

    @Override
    public JsonBody put(String key, Object value) {
        super.put(key, value);
        return this;
    }

    public static JsonBody custom(StatusCode code) { return new JsonBody(code, code.getMsg()); }

    public static JsonBody custom(StatusCode code, String msg) { return new JsonBody(code, msg); }

    public static JsonBody ok() { return custom(StatusCode.SUCCESS); }

    public static JsonBody ok(String msg) { return ok().put("msg", msg); }

    public static JsonBody error() { return custom(StatusCode.ERROR); }

    public static JsonBody error(String msg) { return JsonBody.error().put("msg", msg); }

    @Override
    public String toString() {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.writeValueAsString(this);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

}